/*----------------------------------------------------------------
 *  Author:        Siedin Evgen
 *  Written:       9/2/2013
 *  Last updated:  10/2/2013
 *
 *  Compilation:   javac PercolationStats.java
 *    
 *  Data type PercolationStats
 *  To perform a series of computational experiments wit Percolation
 *
 *  
 *----------------------------------------------------------------*/

public class PercolationStats {

   private double[] results;
   private long times;

   public PercolationStats(int N, int T)
   {
      if (T <= 0 || N <= 0)
      {
         throw new IllegalArgumentException();
      }
      
      times = T;

      results = new double[T];

      for (int i = 0; i < T; i++)
      {
         Percolation p = new Percolation(N);
         double opened = 0;

         while (!p.percolates())
         {
            openOneMoreCell(p, N);
            opened++;
         }

         results[i] = opened / (N * N);
      }
   }

   public double mean()
   {
      return StdStats.mean(results);
   }

   public double stddev()
   {
      return StdStats.stddev(results);
   }

   public double confidenceLo()
   {
      return mean() - 1.96 * stddev() / Math.sqrt(times);
   }

   public double confidenceHi()
   {
      return mean() + 1.96 * stddev() / Math.sqrt(times);
   }

   private void openOneMoreCell(Percolation p, int N)
   {
      int i = StdRandom.uniform(N) + 1;
      int j = StdRandom.uniform(N) + 1;

      while (p.isOpen(i, j))
      {
         i = StdRandom.uniform(N) + 1;
         j = StdRandom.uniform(N) + 1;
      }

      p.open(i, j);
   }

   public static void main(String[] args)
   {
      int N = new Integer(args[0]);
      int T = new Integer(args[1]);

      PercolationStats ps = new PercolationStats(N, T);
      
      System.out.println("mean                    = " + ps.mean());
      System.out.println("stddev                  = " + ps.stddev());
      System.out.println("95% confidence interval = " 
              + ps.confidenceLo() + ", " 
              + ps.confidenceHi());
   }
}
